package com.example.order_service.controller;

import com.example.order_service.service.ProductOrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/v1/order")
public class OrderController {

    private ProductOrderService productOrderService;
    private StringRedisTemplate redisTemplate;

    @Autowired
    public OrderController(ProductOrderService productOrderService,
                           StringRedisTemplate redisTemplate) {
        this.productOrderService = productOrderService;
        this.redisTemplate = redisTemplate;
    }

    @GetMapping("/save")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object save(@RequestParam("user_id") int userId, @RequestParam("product_id") int productId, HttpServletRequest request) {
        String token = request.getHeader("token");
        String cookie = request.getHeader("cookie");

        System.out.println("token is: " + token);
        System.out.println("cookie is: " + cookie);

        Map<String, Object> data = new HashMap<>();
        data.put("code", 0);
        data.put("data", productOrderService.save(userId, productId));
//        int a = 1/0;
        return data;
    }

    // 方法签名要和上面一致
    private Object saveOrderFail(int userId, int productId, HttpServletRequest request) {

        // 监控报警
        String saveOrderKey = "save-order";
        String sendValue = redisTemplate.opsForValue().get(saveOrderKey);

        // 新开一个线程
        new Thread(() -> {
            if (StringUtils.isBlank(sendValue)) {
                System.out.println("紧急短信，用户下单失败，请立刻查找原因");
                // 发送一个http请求，调用短信服务
                redisTemplate.opsForValue().set(saveOrderKey, "save-order-fail", 20, TimeUnit.SECONDS);
            } else {
                System.out.println("已经发送过短信，20s内不重复发送");
            }
        }).start();


        Map<String, Object> msg = new HashMap<>();
        msg.put("code", -1);
        msg.put("msg", "下单人数太多，请稍候重试");
        return msg;
    }
}
